<template>
  <u-upload
    :fileList="fileList"
    @oversize="oversize"
    @afterRead="afterRead"
    @delete="deletePic"
    :multiple="multiple"
    :maxCount="maxCount"
    :accept="accept"
    :maxSize="maxSize"
    previewImage

  >
  </u-upload>
</template>

<script>
import { uploadImage } from '@/api/common';
export default {
  props: {
    maxCount: {
      type: Number,
      default: 10
    },
    maxSize: {
      type: Number,
      default: 10 * 1024 * 1024 // 10 兆
    },
    multiple: {
      type: Boolean,
      default: true
    },
    // all | media | image | file | video (只有微信小程序支持 all、media)
    accept: {
      type: String,
      default: 'image'
    },
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      fileList: []
    };
  },
  model: {
    prop: 'value',
    event: 'input'
  },
  watch: {
    value(val) {
      if (val && !this.fileList.length) {
        console.log('value watch');
        this.fileList = val.split(',').map(e => {
          return {
            url: e,
            status: 'success'
          };
        });
      }
    }
  },
  created() {

  },
  methods: {
    change() {
      const url = this.fileList.filter(e => e.status == 'success').map(e => e.url).join(',');
      this.$emit('input', url);
      this.$emit('change', url);
    },
    // 删除图片
    deletePic(event) {
      this.fileList.splice(event.index, 1);
      this.change();
    },
    oversize(e, err) {
      uni.showModal({
        content: `最大${this.maxSize}兆！`,
        showCancel: false
      });
    },
    // 新增图片
    async afterRead(event) {
      console.log(event, 'event');
      // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
      const lists = [].concat(event.file);
      let fileListLen = this.fileList.length;
      lists.map((item) => {
        this.fileList.push({
          ...item,
          status: 'uploading',
          message: '上传中'
        });
      });
      for (let i = 0; i < lists.length; i++) {
        const result = await uploadImage({ url: lists[i].url, fileType: this.accept });
        let status = 'failed';
        let message = '';
        const item = this.fileList[fileListLen];
        if (!result.err) {
          status = 'success';
        } else {
          message = result.err.errMsg;
        }
        this.fileList.splice(fileListLen, 1, Object.assign(item, {
          status,
          message,
          url: result.url
        }));
        fileListLen++;

        this.change();
      }
    }
  }

};
</script>
